import org.apache.lucene.document.Document;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
import org.junit.Before;
import org.junit.Test;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;

public class QueryHandler {


    private static IndexReader indexReader;
    private static IndexSearcher indexSearcher;


    QueryHandler() throws Exception {
        indexReader = DirectoryReader.open(FSDirectory.open(new File("D:\\Python\\File\\index").toPath()));
        indexSearcher = new IndexSearcher(indexReader);
    }

    @Test
    public void testRangeQuery() throws Exception {
        //创建一个Query对象
        Query query = LongPoint.newRangeQuery("size", 0l, 100l);
//        printResult(query);
    }

//    public static String printResult(Query query) throws Exception {
//        //执行查询
//        StringBuffer stringBuffer= new StringBuffer();
//        TopDocs topDocs = indexSearcher.search(query, 10);
//        System.out.println("总记录数：" + topDocs.totalHits);
//        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
//        for (ScoreDoc doc:scoreDocs){
//            //取文档id
//            int docId = doc.doc;
//            //根据id取文档对象
//            Document document = indexSearcher.doc(docId);
//            String name = document.get("title");
//            String url = document.get("url");
//            String content = document.get("content");
//            String html_link = "<a href\"" + url +"\">" + name + "</a>\n";
//            stringBuffer.append(html_link);
////            <a href="http://www.baidu.com">我是一个超链接</a>
//            String html_content = "<ul>+\n" +
//                    "\t"+content+"\n"
//                    +"</ul>\n";
////            <ul>
////                    在吗？
////            </ul>
//            System.out.print(html_content);
//            stringBuffer.append(html_content);
//        }
//        return stringBuffer.substring(0);
//    }

    @Test
    public void testQueryParser() throws Exception {
        //创建一个QueryPaser对象，两个参数
        QueryParser queryParser = new QueryParser("name", new IKAnalyzer());
        //参数1：默认搜索域，参数2：分析器对象
        //使用QueryPaser对象创建一个Query对象
        Query query = queryParser.parse("这是美丽的哈工大深圳");
        //执行查询
//        printResult(query);
    }

}
